package com.bluezone.dec.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.CacheConstant;
import com.bluezone.dec.common.SystemConstant;
import com.bluezone.dec.configuration.AppConfig;
import com.bluezone.dec.system.service.EnterpriseSecurityStatisticsService;
import com.bluezone.dec.system.service.EnterpriseService;
import com.bluezone.dec.system.service.MonitorAlarmService;
import com.bluezone.dec.utils.TimeTransferUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description 企业安全情况统计service实现层;
 * @Author chenzhaoming;
 * @CreateDate 2018/11/1 10:33;
 * @Company 浙江航天恒嘉数据科技有限公司
 */
@Service
public class EnterpriseSecurityStatisticsImpl implements EnterpriseSecurityStatisticsService {

    @Autowired
    private AppConfig appConfig;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private MonitorAlarmService monitorAlarmService;

    /**
     * 获取标题卡片数据
     *
     * @return
     */
    @Override
    public Map<String, Object> getCardData() {
        if (!redisTemplate.hasKey(CacheConstant.ENTERPRISE_SECURITY_TITLE)) {
            int entAbove = 0;   //规模以上企业数量
            int entDanger = 0;      //危化行业企业
            List<JSONObject> enterpriseBaseList = enterpriseService.getEnterpriseInfo(CacheConstant.ENTERPRISE_BASE).toJavaList(JSONObject.class);

            for (JSONObject jsonObject : enterpriseBaseList) {
                JSONObject base = jsonObject.getJSONObject(SystemConstant.BASE);
                if (null != base) {
                    /*判断是否规模以上企业如果是数量+1*/
                    Boolean scaleOver = base.getBoolean("scaleOver");
                    if (null != scaleOver && scaleOver) {
                        entAbove += 1;
                    }
                    /* 判断行业类别是否是危险化学品*/
                    if ("危险化学品".equals(base.getString("industryCategory"))) {
                        entDanger += 1;
                    }
                }
            }
            Map<String, Object> cardData = new HashMap<>();
            /*获取企业总数*/
            cardData.put("entTotal", enterpriseBaseList.size());
            cardData.put("entAbove", entAbove);
            cardData.put("entDanger", entDanger);
            cardData.put("entMajor", enterpriseService.dangerChemistry());
            redisTemplate.opsForValue().set(CacheConstant.ENTERPRISE_SECURITY_TITLE, JSON.toJSONString(cardData),
                    appConfig.getChartDataCacheTime(), TimeUnit.SECONDS);
        }
        String result = redisTemplate.opsForValue().get(CacheConstant.ENTERPRISE_SECURITY_TITLE);
        return (Map<String, Object>) JSON.parseObject(result, Map.class);
    }

    /**
     * 企业规模等级、标准化等级、监管层级、统计
     *
     * @param levelKey      要统计等级的字段名称
     * @param description   要显示的名字,(如企业规模等级)
     * @param cacheConstant 缓存常量
     * @return
     */
    @Override
    public Map<String, Object> getEnterpriseLevel(String levelKey, String description, String cacheConstant) {
        if (!redisTemplate.hasKey(cacheConstant)) {
            List<String> levelList = enterpriseService.getLevel(levelKey);
            List<JSONObject> enterpriseBaseList = enterpriseService.getEnterpriseInfo(CacheConstant.ENTERPRISE_BASE).toJavaList(JSONObject.class);
            /*统计每一个等级的企业数量*/
            List<Map<String, Object>> levelStatistics = new ArrayList<>();

            if (!StringUtils.isEmpty(levelList)) {

                for (String level : levelList) {
                    Map<String, Object> levelMap = new HashMap<>();

                    long total = 0L;
                    if (!StringUtils.isEmpty(enterpriseBaseList)) {

                        total = enterpriseBaseList.stream().filter(baseStream -> {
                            JSONObject base = baseStream.getJSONObject(SystemConstant.BASE);
                            return (null != base && level.equals(base.getString(levelKey)));
                        }).count();

                    }

                    levelMap.put(SystemConstant.NAME, level);
                    levelMap.put(SystemConstant.VALUE, total);
                    levelStatistics.add(levelMap);
                }

            }

            Map<String, Object> ringLevel = new HashMap<>();
            ringLevel.put(SystemConstant.NAME, description);
            ringLevel.put(SystemConstant.VALUE, levelStatistics);
            redisTemplate.opsForValue().set(cacheConstant, JSON.toJSONString(ringLevel), appConfig.getChartDataCacheTime(), TimeUnit.SECONDS);
        }
        String result = redisTemplate.opsForValue().get(cacheConstant);
        return (Map<String, Object>) JSON.parseObject(result, Map.class);
    }

    /**
     * 统计危险化学品企业类型数量
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getDangerData() {
        if (!redisTemplate.hasKey(CacheConstant.DANGER_DATA)) {
            List<JSONObject> enterpriseBaseList = enterpriseService.getEnterpriseInfo(CacheConstant.ENTERPRISE_BASE).toJavaList(JSONObject.class);
            /*行业类型的集合*/
            List<String> industryCategorySet = enterpriseService.getLevel(SystemConstant.DANGEROUS_TYPE);
            List<Map<String, Object>> dangerData = new ArrayList<>();

            if (!StringUtils.isEmpty(industryCategorySet)) {

                /*遍历行业类型的集合*/
                for (String industryCategory : industryCategorySet) {
                    Map<String, Object> industryCategoryMap = new HashMap<>();

                    long total = 0L;
                    if (!StringUtils.isEmpty(enterpriseBaseList)) {

                        total = enterpriseBaseList.stream().filter(baseStream -> {
                            JSONObject base = baseStream.getJSONObject(SystemConstant.BASE);
                            return (null != base && industryCategory.equals(base.getString(SystemConstant.DANGEROUS_TYPE)));
                        }).count();

                    }

                    industryCategoryMap.put(SystemConstant.NAME, industryCategory);
                    industryCategoryMap.put(SystemConstant.VALUE, total);
                    dangerData.add(industryCategoryMap);
                }

            }

            redisTemplate.opsForValue().set(CacheConstant.DANGER_DATA, JSON.toJSONString(dangerData), appConfig.getChartDataCacheTime(), TimeUnit.SECONDS);
        }
        String result = redisTemplate.opsForValue().get(CacheConstant.DANGER_DATA);
        return (List<Map<String, Object>>) JSON.parseObject(result, List.class);
    }

    /**
     * 报警月份统计，统计近一年每个月的报警数量
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> alarmRecord() {
        if (!redisTemplate.hasKey(CacheConstant.ALARM_RECORD)) {
            /*监控预警所有的报警信息*/
            List<JSONObject> alarmRecordList = monitorAlarmService.monitoringAndWarning(SystemConstant.ALARM_RECORD);
            /*最近12个月的月份的集合*/
            List<String> dateList = TimeTransferUtils.getDayList();
            List<Map<String, Object>> dateTotalList = new ArrayList<>();

            for (String date : dateList) {

                long total = 0L;
                if (!StringUtils.isEmpty(alarmRecordList)) {
                    total = alarmRecordList.stream().filter(jsonObject -> date.equals(jsonObject.getString("create_date").substring(0, 7))).count();
                }

                Map<String, Object> dateMap = new HashMap<>();
                dateMap.put(SystemConstant.NAME, date);
                dateMap.put(SystemConstant.VALUE, total);
                dateTotalList.add(dateMap);
            }

            redisTemplate.opsForValue().set(CacheConstant.ALARM_RECORD, JSON.toJSONString(dateTotalList), appConfig.getChartDataCacheTime(), TimeUnit.SECONDS);
        }
        String result = redisTemplate.opsForValue().get(CacheConstant.ALARM_RECORD);
        return (List<Map<String, Object>>) JSON.parseObject(result, List.class);
    }

    /**
     * 获取报警类型的集合
     * 预警级别的集合
     *
     * @param urlKey    指向url的key值
     * @param fieldName 所统计字段名称
     * @return
     */
    @Override
    public List<Map<String, Object>> typeStatistics(String urlKey, String fieldName, String cacheConstant) {
        if (!redisTemplate.hasKey(cacheConstant)) {
            List<JSONObject> typeArray = monitorAlarmService.monitoringAndWarning(urlKey);
            List<String> typeList = monitorAlarmService.typeSet(urlKey, fieldName);
            List<Map<String, Object>> typeStatistics = new ArrayList<>();

            if (!StringUtils.isEmpty(typeList)) {

                for (String type : typeList) {

                    long total = 0L;
                    if (!StringUtils.isEmpty(typeArray)) {
                        total = typeArray.stream().filter(jsonObject -> type.equals(jsonObject.getString(fieldName))).count();
                    }

                    Map<String, Object> typeMap = new HashMap<>();
                    typeMap.put(SystemConstant.NAME, type);
                    typeMap.put(SystemConstant.VALUE, total);
                    typeStatistics.add(typeMap);
                }

            }

            redisTemplate.opsForValue().set(cacheConstant, JSON.toJSONString(typeStatistics), appConfig.getChartDataCacheTime(), TimeUnit.SECONDS);
        }
        String result = redisTemplate.opsForValue().get(cacheConstant);
        return (List<Map<String, Object>>) JSON.parseObject(result, List.class);
    }

    /**
     * 报警行业统计
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> industryStatistics() {
        if (!redisTemplate.hasKey(CacheConstant.INDUSTRY_STATISTICS)) {
            /*获取所有报警记录id和其所属的企业Id*/
            List<JSONObject> recordArray = monitorAlarmService.monitoringAndWarning(SystemConstant.INDUSTRY_STATISTICS);
            /*获取企业的基础信息*/
            List<JSONObject> enterpriseBaseList = enterpriseService.getEnterpriseInfo(CacheConstant.ENTERPRISE_BASE).toJavaList(JSONObject.class);
            /*获取所有的行业类型*/
            List<String> industrySet = enterpriseService.getLevel(SystemConstant.DANGEROUS_TYPE);
            List<Map<String, Object>> industryList = new ArrayList<>();
            for (String industry : industrySet) {
                long total = 0L;
                if (!StringUtils.isEmpty(recordArray)) {
                    total = recordArray.stream().filter(jsonObject -> {
                        String creditCode = jsonObject.getString(SystemConstant.ENTERPRISE_CODE);
                        String typeValue = enterpriseBaseList.stream()
                                .filter(e -> creditCode.equals(e.getString(SystemConstant.ENTERPRISE_CODE)))
                                .findAny()
                                .map(m -> m.getJSONObject(SystemConstant.BASE))
                                .map(m -> m.getString(SystemConstant.DANGEROUS_TYPE))
                                .orElse("");
                        return industry.equals(typeValue);
                    }).count();
                }

                Map<String, Object> industryMap = new HashMap<>();
                industryMap.put(SystemConstant.NAME, industry);
                industryMap.put(SystemConstant.VALUE, total);
                industryList.add(industryMap);
            }

            redisTemplate.opsForValue().set(CacheConstant.INDUSTRY_STATISTICS, JSON.toJSONString(industryList), appConfig.getChartDataCacheTime(), TimeUnit.SECONDS);
        }
        String result = redisTemplate.opsForValue().get(CacheConstant.INDUSTRY_STATISTICS);
        return (List<Map<String, Object>>) JSON.parseObject(result, List.class);
    }

}
